from flask import Flask
from flask_session import Session
from exts import db, cache
import setting
from blueprints import (Blog_bp, ShopType_bp, User_bp, Shop_bp, Voucher_bp,
                        Voucher_order_bp, Upload_bp, Follow_bp)


def creat_app():
    app = Flask(__name__)
    app.config.from_object(setting)
    db.init_app(app)
    cache.init_app(app, config=setting.flask_caching_config)
    Session(app)  # 替换为直接使用redis存储session，方便用户数据的修改
    app.register_blueprint(Blog_bp)
    app.register_blueprint(ShopType_bp)
    app.register_blueprint(User_bp)
    app.register_blueprint(Shop_bp)
    app.register_blueprint(Voucher_bp)
    app.register_blueprint(Voucher_order_bp)
    app.register_blueprint(Upload_bp)
    app.register_blueprint(Follow_bp)
    return app


app = creat_app()

from setting import Prefixs
from flask import request
from utils.redis import Redis


@app.before_request
def before_request_user():
    token = request.headers.get("Authorization", default='')
    token_key = Prefixs.user_token_prefix + token
    if token and Redis.exists(token_key):  # 用户访问时刷新session缓存session(tokenKey: userinfo)
        Redis.expire(token_key, 60 * 60 * 3)  # 重置为三个个小时



# import click
# @app.cli.command()
# @click.option('-l', '--length')
# @click.option('-n', default='h')
# def ptr(length, n):
#     print(length, n)

if __name__ == '__main__':
    app.run(port=8081, debug=False, threaded=True)
